import json
from flask import request, jsonify

from BlackChess import BlackChess
from WhiteChess import WhiteChess
from Subject import Subject


def judge(i, j):
    result = json.loads(request.form.get('data'))
    # result = request.form.get('data')

    checkBox = result.get('checkBox')
    value = checkBox[i][j]
    winner = 0
    # flag = result.get('flag')
    flag = False
    for x in range(j - 4, j + 5):
        if x >= 0 and x + 4 < 15:
            if checkBox[i][x] == value and checkBox[i][x + 1] == value and checkBox[i][x + 2] == value and checkBox[i][
                x + 3] == value and checkBox[i][x + 4] == value:
                flag = True
                break
                pass
    for x in range(i - 4, i + 5):  # 纵向有没有出现5连（在边缘依次逐一遍历，是否五个棋子的类型一样）
        if x >= 0 and x + 4 < 15:
            if checkBox[x][j] == value and \
                    checkBox[x + 1][j] == value and \
                    checkBox[x + 2][j] == value and \
                    checkBox[x + 3][j] == value and \
                    checkBox[x + 4][j] == value:
                flag = True
                break
                pass

        # 先判断右斜方向的对角下输赢 x 列轴， y是行轴 ， i 是行 j 是列（右斜向）（在边缘依次逐一遍历，是否五个棋子的类型一样）
    for x, y in zip(range(j + 4, j - 5, -1), range(i - 4, i + 5)):
        if x >= 0 and x + 4 < 15 and y + 4 >= 0 and y < 15:
            if checkBox[y][x] == value and \
                    checkBox[y - 1][x + 1] == value and \
                    checkBox[y - 2][x + 2] == value and \
                    checkBox[y - 3][x + 3] == value and \
                    checkBox[y - 4][x + 4] == value:
                flag = True

        # 2、判断左斜对角下输赢 x 列轴， y是行轴 ， i 是行 j 是列（左斜向）（在边缘依次逐一遍历，是否五个棋子的类型一样）
    for x, y in zip(range(j - 4, j + 5), range(i - 4, i + 5)):
        if x >= 0 and x + 4 < 15 and y >= 0 and y + 4 < 15:
            if checkBox[y][x] == value and \
                    checkBox[y + 1][x + 1] == value and \
                    checkBox[y + 2][x + 2] == value and \
                    checkBox[y + 3][x + 3] == value and \
                    checkBox[y + 4][x + 4] == value:
                flag = True

    if flag:
        subject = Subject()
        black_chess = BlackChess(x, y, subject)
        white_chess = WhiteChess(x, y, subject)
        if value == 2:
            winner = 1
            subject.setWiner(white_chess)
        else:
            winner = 2
            subject.setWiner(black_chess)
    return winner
